/**
 * Created by Tink Cai on 7/27/2017.
 */
angular.module('tinkcai.shiai', []).controller('shiaiController', function ($scope, $http) {
    $http({
        method: 'GET', url: '/shiai/shiai.json?' + new Date().getTime()
    }).then(function successCallback(response) {
        $scope.shiai = angular.copy(response.data);
    }, function errorCallback(response) {
        $scope.shiai = angular.copy([]);
    });

    $scope.currentIndex = 0;
    $scope.model = {};

    $scope.changeTitle = function (titleModel) {
        $scope.titleModel = angular.copy(titleModel);
        mui('#titleList').popover('toggle');
        mui('#subTitleList').popover('toggle');
    };

    $scope.changeSubTitle = function (subtitleModel) {
        $scope.model = angular.copy(subtitleModel);
        mui('#subTitleList').popover('toggle');
        $scope.currentIndex = 0;
    };

    $scope.selectAnswer = function (option, item, index) {
        if (item.answered) {
            return;
        }
        if (!option.isCorrect) {
            item.options.forEach(function (opt) {
                if (opt.isCorrect) {
                    opt.showAnswer = true;
                }
            });
        }
        option.showAnswer = true;
        item.answered = true;
    };

    $scope.next = function (opt) {
        if (opt.answered) {
            if ($scope.currentIndex >= $scope.model.exam.length - 1) {
                mui.alert('您已经完成了所有题目');
            }
            $scope.currentIndex++;
        }
    }

    var progressbar = mui('#bar');
    mui(progressbar).progressbar().setProgress(0);

    $scope.$watch('currentIndex', function (index) {
        if ($scope.model.exam) {
            mui(progressbar).progressbar().setProgress(index / $scope.model.exam.length * 100);
        }
        else {
            mui(progressbar).progressbar().setProgress(0);
        }
    });

    $scope.redirect = function () {
        var backUrl = document.getElementById('backUrl').value;
        if (backUrl) {
            location.href = backUrl;
        } else {
            mui.back();
        }
    }
});

